// borrow_record.dart
import 'package:flutter/material.dart';
import 'storage_service.dart'; // 确保导入存储服务
import 'models.dart' as my_models;

class BorrowList extends StatefulWidget {
  @override
  _BorrowListState createState() => _BorrowListState();
}

class _BorrowListState extends State<BorrowList> {
  List<my_models.BorrowRecord> _records = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadRecords();
  }

  Future<void> _loadRecords() async {
    try {
      setState(() => _isLoading = true);
      print('🔄 开始加载借阅记录');

      final rawRecords = await StorageService.loadBorrowRecords();
      print('✅ 加载完成，原始记录数: ${rawRecords.length}');

      // 打印原始数据用于调试
      print('🔍 原始借阅记录数据:');
      for (int i = 0; i < rawRecords.length; i++) {
        print('[$i]: ${rawRecords[i]}');
      }

      if (rawRecords.isEmpty) {
        setState(() {
          _records = [];
          _isLoading = false;
        });
        print('ℹ️ 无借阅记录');
        return;
      }

      int startIndex = 0;

      // 检查标题行
      if (rawRecords[0][0] == 'bookId') {
        startIndex = 1;
        print('📋 发现标题行');
      }

      List<my_models.BorrowRecord> loadedRecords = [];
      for (int i = startIndex; i < rawRecords.length; i++) {
        final row = rawRecords[i];

        // 确保行格式正确
        if (row.length < 5) {
          print('⚠️ 行数据不完整，跳过: $row');
          continue;
        }

        try {
          // 解析日期
          DateTime borrowDate;
          DateTime dueDate;

          try {
            borrowDate = DateTime.parse(row[2].toString());
          } catch (e) {
            print('❌ 解析借阅日期失败: ${row[2]}');
            borrowDate = DateTime.now();
          }

          try {
            dueDate = DateTime.parse(row[3].toString());
          } catch (e) {
            print('❌ 解析应还日期失败: ${row[3]}');
            dueDate = DateTime.now().add(Duration(days: 30));
          }

          // 创建记录对象
          final record = my_models.BorrowRecord(
            bookId: row[0].toString(),
            bookTitle: row[1].toString(),
            borrowDate: borrowDate,
            dueDate: dueDate,
            isReturned: (row[4].toString().toLowerCase() == 'true'),
          );

          loadedRecords.add(record);
          print('📝 添加记录: ${record.bookTitle} (ID: ${record.bookId})');
        } catch (e) {
          print('❌ 创建记录失败: $e\n行数据: $row');
        }
      }

      setState(() {
        _records = loadedRecords;
        _isLoading = false;
      });

      print('🔄 加载完成，有效记录数: ${_records.length}');
    } catch (e) {
      print('❌ 加载借阅记录失败: $e');
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('❌ 加载借阅记录失败: ${e.toString()}')));
    }
  }

  Future<void> _returnBook(my_models.BorrowRecord record) async {
    try {
      print('🔄 开始归还图书: ${record.bookTitle} (ID: ${record.uniqueId})');

      // 1. 加载所有记录
      List<List<dynamic>> records = await StorageService.loadBorrowRecords();
      print('🔍 加载记录成功，数量: ${records.length}');

      // 2. 找到并更新对应记录
      bool recordUpdated = false;

      for (int i = 0; i < records.length; i++) {
        // 跳过标题行
        if (i == 0 && records[i][0] == 'bookId') continue;

        // 确保行有足够的数据
        if (records[i].length < 5) continue;

        // 创建当前行记录的唯一ID
        final rowBookId = records[i][0].toString();
        DateTime rowBorrowDate;

        try {
          rowBorrowDate = my_models.BookDateUtils.parseDate(records[i][2].toString());
        } catch (e) {
          print('❌ 解析日期失败: ${records[i][2]}');
          continue;
        }

        final rowUniqueId = '$rowBookId-${rowBorrowDate.millisecondsSinceEpoch}';

        // 使用唯一ID进行比较
        if (rowUniqueId == record.uniqueId) {
          records[i][4] = 'true'; // 标记为已归还
          recordUpdated = true;
          print('🔄 找到并更新记录: ${record.bookTitle}');
          print('  记录唯一ID: $rowUniqueId');
          break;
        }
      }

      if (!recordUpdated) {
        // 尝试回退匹配方式
        bool fallbackUpdated = false;
        for (int i = 0; i < records.length; i++) {
          if (i == 0 && records[i][0] == 'bookId') continue;
          if (records[i].length < 5) continue;

          final rowBookId = records[i][0].toString();
          final rowBookTitle = records[i][1].toString();

          // 回退匹配：只比较ID和标题
          if (rowBookId == record.bookId && rowBookTitle == record.bookTitle) {
            records[i][4] = 'true';
            fallbackUpdated = true;
            print('⚠️ 使用回退方式更新记录: ${record.bookTitle}');
            break;
          }
        }

        if (!fallbackUpdated) {
          throw Exception('未找到对应的借阅记录: ${record.bookTitle} (唯一ID: ${record.uniqueId})');
        }
      }

      // 3. 保存更新后的记录
      await StorageService.saveBorrowRecords(records);
      print('💾 保存记录成功');

      // 4. 更新图书可借数量
      final book = my_models.allBooks.firstWhere(
            (b) => b.id == record.bookId,
        orElse: () {
          print('⚠️ 找不到对应图书: ID=${record.bookId}');
          return my_models.Book(
            id: record.bookId,
            title: record.bookTitle,
            author: '未知',
            coverUrl: '',
            description: '',
            isbn: '',
            publisher: '',
            publishYear: DateTime.now().year,
            totalCopies: 1,
            availableCopies: 0,
          );
        },
      );

      setState(() {
        book.availableCopies++;
        record.isReturned = true;
        // 从当前列表中移除已归还的记录
        _records = _records.where((r) => !r.isReturned).toList();
      });

      print('📈 图书可借数量增加: ${book.availableCopies}');

      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('✅ 已归还《${record.bookTitle}》')));
    } catch (e) {
      print('❌ 归还图书失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('❌ 归还失败: ${e.toString()}')));
    }
  }

  @override
  Widget build(BuildContext context) {
    final currentRecords = _records.where((r) => !r.isReturned).toList();

    return Scaffold(
      appBar: AppBar(
        title: Text('借阅记录'),
        actions: [
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: _loadRecords,
            tooltip: '刷新列表',
          ),
        ],
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : currentRecords.isEmpty
          ? RefreshIndicator(
        onRefresh: _loadRecords,
        child: SingleChildScrollView(
          physics: AlwaysScrollableScrollPhysics(),
          child: Center(
            heightFactor: 10,
            child: Text("暂无借阅记录"),
          ),
        ),
      )
          : RefreshIndicator(
        onRefresh: _loadRecords,
        child: ListView.builder(
          itemCount: currentRecords.length,
          itemBuilder: (context, index) => BorrowRecordItem(
            record: currentRecords[index],
            onReturn: () => _returnBook(currentRecords[index]),
          ),
        ),
      ),
    );
  }
}

class BorrowRecordItem extends StatelessWidget {
  final my_models.BorrowRecord record;
  final VoidCallback onReturn;

  const BorrowRecordItem({
    Key? key,
    required this.record,
    required this.onReturn,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: ListTile(
        leading: Icon(Icons.book, color: Theme.of(context).primaryColor),
        title: Text(record.bookTitle),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("借阅日期: ${record.borrowDate.toString().substring(0, 10)}"),
            Text("应还日期: ${record.dueDate.toString().substring(0, 10)}"),
            if (record.dueDate.isBefore(DateTime.now()))
              Text("已逾期", style: TextStyle(color: Colors.red)),
          ],
        ),
        trailing: ElevatedButton(
          onPressed: onReturn,
          child: Text("归还"),
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.green,
            foregroundColor: Colors.white,
          ),
        ),
      ),
    );
  }
}